package com.mes.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.mes.cloud.dao.BcViewDAO;
import com.mes.cloud.dao.BmeBcAppletDAO;
import com.mes.cloud.dto.BcViewDTO;
import com.mes.cloud.dto.BmeBcAppletDTO;
import com.mes.cloud.service.BcViewService;
import com.mes.cloud.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表字段
 *
 * @author wxm
 * @Time 2019-5-22
 */
@Service
public class BcViewServiceImpl implements BcViewService {
    private static final Logger LOGGER = LoggerFactory.getLogger(BcViewServiceImpl.class);
    @Autowired
    private BcViewDAO bcViewDAO;

    @Autowired
    private BmeBcAppletDAO bmeBcAppletDAO;

    @Override
    public List<BcViewDTO> getBcViewList(Map<Object, Object> condition) {
        return bcViewDAO.getBcViewList(condition);
    }

    @Override
    public long getBcViewCount(Map<Object, Object> condition) {

        return bcViewDAO.getBcViewCount(condition);
    }

    @Override
    public boolean exists(Map<Object, Object> condition) {
        boolean returnB = false;
        long count = getBcViewCount(condition);
        if (count > 0) {
            returnB = true;
        }
        return returnB;
    }

    @Override
    public long insertBcView(BcViewDTO bcViewDTO) throws Exception {
        //code数据库唯一  判断code是否已经存在
        Map<Object, Object> condition = new HashMap<Object, Object>();
        condition.put("code", bcViewDTO.getCode());
        //如果存在
        if (exists(condition)) {
            throw new Exception("code exists!");
        }
        //生成主键
        bcViewDTO.setId(UuId.getShortUuid());
        return bcViewDAO.insertBcView(bcViewDTO);
    }

    @Override
    public long updateBcView(BcViewDTO bcViewDTO) {

        return bcViewDAO.updateBcView(bcViewDTO);
    }

    @Override
    public long delBcViewById(String id) {

        return bcViewDAO.delBcViewById(id);
    }

    @Override
    public BcViewDTO getBcViewById(String id) {

        return bcViewDAO.getBcViewById(id);
    }

    @Override
    public CommPager<BcViewDTO> getBcViewListPage(Map<Object, Object> condition) {
        int pageIndex = condition.get("pageIndex") == null ? 0 : Integer.valueOf(condition.get("pageIndex").toString());
        int pageSize = condition.get("pageSize") == null ? 10 : Integer.valueOf(condition.get("pageSize").toString());
        Page<BcViewDTO> page = PageHelper.startPage(pageIndex, pageSize, true);
        List<BcViewDTO> dictList = bcViewDAO.getBcViewList(condition);
        CommPager<BcViewDTO> pageResult = new CommPager<>(page, dictList);
        return pageResult;
    }

    @Override
    public long batchDelete(Map<Object, Object> map) throws Exception {
        if (map.get("ids") == null) {
            throw new Exception("ids不能为空");
        }
        return bcViewDAO.batchDelete((List<String>) map.get("ids"));
    }

    @Override
    public long enable(Map<Object, Object> map) throws Exception {
        if (map.get("id") == null || map.get("isEnable") == null) {
            throw new Exception("参数异常");
        }
        return bcViewDAO.enable(map);
    }

    @Override
    public Long batchEnable(Map<Object, Object> map) throws Exception {
        if (map.get("ids") == null) {
            throw new Exception("ids不能为空");
        }
        return bcViewDAO.batchEnable((List<Long>) map.get("ids"));
    }

    @Override
    public int importExcel(MultipartFile file) throws Exception {
        String rooPath = this.getClass().getResource("/").getPath();
        //复制文件到static目录
        String path = rooPath + "/static";
        String fileName = FileUploadUtils.uploadFile(file, path);
        String filePath = FileUploadUtils.uploadFile(file, path, fileName);
        FileInputStream fis = null;
        fis = new FileInputStream(filePath);
        // 创建工具类.
        ExcelUtil<BcViewDTO> util = new ExcelUtil<BcViewDTO>(BcViewDTO.class);
        List<BcViewDTO> paramList = util.importExcel(fileName, fis);
        HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
        if (StringUtils.isEmpty(paramList)) {
            throw new Exception("数据为空！");
        }
        for (BcViewDTO bmeBcSubDTO : paramList) {
            if (StringUtils.isEmpty(bmeBcSubDTO.getId())) {
                bmeBcSubDTO.setId(UuId.getShortUuid());
            } else {
                objectObjectHashMap.put("id", bmeBcSubDTO.getId());
                long count = bcViewDAO.getBcViewCount(objectObjectHashMap);
                if (count > 0) {
                    throw new Exception("数据已经存在！");
                }
            }
        }
        return bcViewDAO.insertExcel(paramList);
    }

    @Override
    public void exportFile(Map<Object, Object> map, HttpServletResponse response) throws Exception {
        List<BcViewDTO> list = bcViewDAO.getBcViewList(map);
        if (list.size() == 0) {
            throw new Exception("导出数据为空！");
        }
        // 创建工具类
        ExcelUtil<BcViewDTO> util = new ExcelUtil<BcViewDTO>(BcViewDTO.class);
        // 导出
        String topName = DateUtil.getDateTime("yyyyMMddHHmmss");
        util.exportFile(list, DateUtil.getDateTime(topName), topName, response);
    }

    @Override
    public BcViewDTO getByCode(String code) {
        //通过code获取bcview
        BcViewDTO bcViewDTO = bcViewDAO.getByCode(code);
//        Map<Object, Object> condition = new HashMap<Object, Object>();
//        condition.put("viewId", bcViewDTO.getId());
//        //获取bc子表BcApplet数据
//        List<BmeBcAppletDTO> list = bmeBcAppletDAO.getList(condition);
//        Map<String, Map<String, Object>> map = listMap(list);
//        //BcApplet数据填充到bcViewDTO
//        bcViewDTO.setJsonconfig(JSONObject.toJSONString(map));
        return bcViewDTO;
    }

    /**
     * @param list
     * @Description List按applet分组，同applet下数据用BmeBcAppletDTO 字段code做key BmeBcAppletDTO为value
     * @date: 2019/6/27 16:57
     * @return: java.util.Map<java.lang.String   ,   java.util.Map   <   java.lang.String   ,   com.mes.cloud.dto.String>>
     */
    public Map<String, Map<String, Object>> listMap(List<BmeBcAppletDTO> list) {
        Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>();
        String tempApplet = null;
        Object jsonConfig = null;
        if (list != null && list.size() > 0) {
            for (BmeBcAppletDTO bmeBcAppletDTO : list) {
                //获取applet
                tempApplet = bmeBcAppletDTO.getApplet();
                //获取jsonConfig
                try {
                    jsonConfig = JSON.parse(bmeBcAppletDTO.getJsonconfig());
                } catch (Exception e) {
                    LOGGER.error(e.toString());
                }
                //判断是否存在  按applet分组
                if (map.containsKey(tempApplet)) {
                    //追加
                    map.get(tempApplet).put(bmeBcAppletDTO.getCode(), jsonConfig);
                } else {
                    //新建
                    Map<String, Object> mapTemp = new HashMap<String, Object>();
                    mapTemp.put(bmeBcAppletDTO.getCode(), jsonConfig);
                    map.put(tempApplet, mapTemp);
                }
            }
        }
        return map;
    }
}
